<?php

namespace catchAdmin\storehouse\model;

use catcher\base\CatchModel;
use catchAdmin\storehouse\model\search\TraySearch;
use catcher\CatchAuth;
use think\facade\Cache;
use think\facade\Db;
/**
 *
 * @property int $id
 * @property string $warehousing_id
 * @property string $warehousing_son_id
 * @property string $tray_id
 * @property string $config_id
 * @property int $number
 * @property int $box_number
 * @property int $created_at
 * @property int $updated_at
 * @property int $sort
 * @property int $isstatus
 * @property string $status
 * @property string $goods_status
 * @property int $deleted_at
 * @property int $creator_id
 * @property int $tenant_id
 */
class Tray extends CatchModel
{
    use TraySearch;
    public $field = [
        // ID
        'id',
        // 入库主单编号
        'warehousing_id',
        // 入库明细编号
        'warehousing_son_id',
        // 托盘码
        'tray_id',
        // 库位编号(关联库位表）
        'config_id',
        // 入库数量
        'number',
        // 入库箱数
        'box_number',
        // 创建时间
        'created_at',
        // 更新时间
        'updated_at',
        // 入库状态:0=未入库,1=全部入库
        'status',
        // 货物状态
        'goods_status',
        // 删除时间
        'deleted_at',
        // 创建人ID
        'creator_id',
        // 商户
        'tenant_id',
        'move_id',
        'batch_number',
        'type',
        'is_system_distribution',
        'LOT1',
        'LOT2',
        'LOT3',
    ];
    
    public $name = 'db_tray';
    /**
   * 列表
   * @throws \think\db\exception\DbException
   * @return \think\Paginator
   */
    public function getList($tenant_id = 0)
    {
        $where = [];
        if($tenant_id !== 0){
            $where[]=['t.tenant_id','=',$tenant_id];
        }

        return $this->catchSearch()
                    ->alias('t')
                    ->leftJoin('db_warehouse_config c','t.config_id = c.config_id')
                    ->order('t.id','desc')
                    ->where($where)
                    ->field(['t.warehousing_id,t.id,t.warehousing_son_id,t.tray_id,t.number,t.box_number,t.status,t.goods_status,t.config_id,c.name as config_name,c.parent_id as wc_parent_id,t.LOT1,t.LOT2,t.LOT3'])
                    ->paginate()
                    ->each(function (&$item){
                        $item['products'] = Db::table('db_warehousing_product')
                            ->field('goods_id,goods_name,goods_Cname,goods_Ename,manufacturer_id,manufacturer_name,supplier_id,supplier_name,packing_num,unit_name,number,box_number,status,tray_id,specification')
                            ->where(['warehousing_son_id'=>$item['warehousing_son_id'],'deleted_at'=>0,'tray_id'=>$item['tray_id']])
                            ->select();
                        $warehouse_config_level2 = Db::table('db_warehouse_config')->where('id',$item['wc_parent_id'])->find();
                        $warehouse_config_level1 = Db::table('db_warehouse_config')->where('id',$warehouse_config_level2['parent_id'])->find();
                        $item['config_full_name'] = implode('-',[$warehouse_config_level1['name'],$warehouse_config_level2['name'],$item['config_name']]);
                        $item['pallet_no'] = Db::table('db_warehousing_sn')
                            ->where([
                                'warehousing_son_id'=>$item['warehousing_son_id'],
                                'deleted_at'=>0,
                                'tray_id'=>$item['tray_id']
                            ])->value('pallet_no');

                        $item['batch_no']= Db::table('db_warehousing')
                            ->where([
                                'warehousing_id' => $item['warehousing_id'],
//                        'pallet_no' => $item['pallet_no'],
                            ])->value('batch_no');

                    });
    }

    public function getTrayList($is_tree = true){

//        if(null != Cache::get('tray_list')){
//            return Cache::get('tray_list');
//        }

        $user = (new CatchAuth())->user();

        $where = [];
        $where[] =  ['deleted_at','=',0];
        $where[] = ['tenant_id','=',$user->tenant_id];

        $field = ['config_id','name','level','parent_id','id'];
        $warehouse_config =  Db::table('db_warehouse_config')
            ->field($field)->where($where)
            ->order('sort','desc')->select()->toArray();

        //$result = [];
        //Cache::set('tray_list', $result, 86400 * 30);
        return $is_tree == true ?  $this->generateTree($warehouse_config,0) : $warehouse_config;
    }

    public function generateTree($data,$parent_id = 0)
    {
        $tree = [];
        $newData = array_combine(array_column($data,'id'),$data);

        foreach ($newData as $key => $datum) {
            $newData[$key]['value'] = $datum['id'];
            $newData[$key]['label'] = $datum['name'];
            if ($datum['parent_id'] == $parent_id) {
                //根节点直接把地址放到新数组中
                $tree[] = &$newData[$key];
            } else {
                //不是根节点的将自己的地址放到父级的child节点
                $newData[$datum['parent_id']]['children'][] = &$newData[$key];
                //$newData[$datum['parent_id']]['son'][] = &$newData[$key];
            }
        }
        return $tree;
    }

    public function digui($array, $parent_id=0){

        $list = [];
        foreach ($array as &$value) {
            if ($value['parent_id'] == $parent_id) {
                if(!empty($lst =  $this->digui($array, $value['id']))){
                    $value['children'] = $lst;
                    $value['son'] = $lst;
                }

                $list[] = $value;
            }
        }
        return $list;
    }

    //无分页
    public function getAttrList($tenant_id = 0)
    {
        $where = [];
        if($tenant_id !== 0){
            $where[]=['t.tenant_id','=',$tenant_id];
        }

        $data = [];
        $data['tray_info'] =  $this->catchSearch()
            ->alias('t')
            ->leftJoin('db_warehouse_config c','t.config_id = c.config_id')
            ->order('t.id','desc')
            ->where($where)
            ->field(['t.id,t.warehousing_son_id,t.tray_id,t.number,t.box_number,t.status,t.goods_status,t.config_id,c.name as config_name,c.id as warehouse_config_id,c.config_id as warehouse_config_c_id,c.parent_id as warehouse_config_p_id'])
            ->select()->toArray()
       ;

        foreach ($data['tray_info'] as $key => &$value){
            $config_level2 = Db::table('db_warehouse_config')->field('id,config_id,parent_id')->where('id',$value['warehouse_config_p_id'])->find();

            $config_level1 =  Db::table('db_warehouse_config')->where('id',$config_level2['parent_id'])->value('config_id');

            $value['config1'][] = $config_level1;
            $value['config1'][] = $config_level2['config_id'];



            //$value['config1'][1] = $config_level1['config_id'];
           // $value['config1'][0] = Db::table('db_warehouse_config')->where('id',$config_level1['parent_id'])->value('config_id');
            $value['config2'] = $value['warehouse_config_c_id'];
            $value['configData2'] = Db::table('db_warehouse_config')->field('name,config_id')->where('parent_id',$value['warehouse_config_p_id'])->select()->toArray();
//            $value['warehouse_config_c_id'];
        }

        //反转数组，让零头放在下面
        $data['tray_info'] = array_reverse($data['tray_info']);


       $data['warehouse_config_info'] = $this->getTrayList();

       return $data;
    }

    public function getTrayIdsByWarehousingSonId($warehousing_son_id,$is_unique= false){
        $result = Db::table('db_tray')
            ->where('warehousing_son_id',$warehousing_son_id)
            ->where('status',1)
            ->where('deleted_at',0)
            ->column('tray_id')
        ;

        return $is_unique ? array_values(array_unique($result)) : $result;
    }
}